package com.feib.soeasy.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.feib.soeasy.model.ColumnValidateError;
import com.feib.soeasy.model.FormatDefinition;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.LabelValue;
import com.feib.soeasy.model.PayerTemp;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.ColumnValidateErrorService;
import com.feib.soeasy.service.FormatDefinitionService;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.PayerTempService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.UploadFileService;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;


/**
 * @title (#)Soez9004ActionBean.java<br>
 * @description 上傳記錄查詢Controller<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/12 create by Jimmy Liu<br>
 */
public class Soez9004ActionBean extends BaseActionBean implements ValidationErrorHandler
{

    private static final String DEFAULT_JSP = "/WEB-INF/views/soez9004/soez9004.jsp";
    /**
     * 帳單上傳記錄查詢結果畫面
     */
    private static final String AJAX_QUERY_JSP = "/WEB-INF/views/soez9004/soez9004List.jsp";
    
    /**
     * 檔案內容
     */
    private static final String AJAX_QUERY_PAYMENT_JSP = "/WEB-INF/views/soez9004/paymentList.jsp";
    
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez9004/groupPopUpList.jsp";
    
    /**
     * [業者代號]改變後觸發重製[收款類別]選項結果
     */
    private static final String AJAX_FORMT_DEF_OPTIONS_JSP = "/WEB-INF/views/soez9004/formatDefinitionOptions.jsp";
    
    /**
     * 檔案錯誤原因結果畫面
     */
    private static final String AJAX_QUERY_COLUMN_ERROR_JSP = "/WEB-INF/views/soez9004/columnValidateErrors.jsp";

    /**
     * 查詢繳款人
     */
    private static final String AJAX_QUERY_PAYER_JSP = "/WEB-INF/views/soez9004/payerTempList.jsp";

    
    
    /**
     * 查詢條件
     */
    @ValidateNestedProperties({
        @Validate(field="uploadFilePk", required=true, on={"doAjaxQueryFilePayments", "doAjaxQueryFileErrorReasons"}  )        
        , @Validate(field="group.groupNo", required=true, on={"doAjaxQuery"})
        , @Validate(field="uploadDate", converter=DateTypeConverter.class )
    })
    private UploadFile qryUploadFile;

    /** 
     * 查詢條件-上傳日期起
     */
    @Validate( required=true, on={"doAjaxQuery"}, converter=DateTypeConverter.class)
    private Date qryUploadFrom;

    /**
     * 查詢條件-上傳日期迄
     */
    @Validate( required=true, on={"doAjaxQuery"}, converter=DateTypeConverter.class)
    private Date qryUploadTo;

    /**
     * 查詢結果
     */
    private PaginatedList<UploadFile> queryResult;

    /**
     * 檔案帳單明細查詢結果
     */
    private PaginatedList<Payment> queryPaymentResult;

    /**
     * 檔案錯誤原因明細查詢結果
     */
    private PaginatedList<ColumnValidateError> queryColumnValidateErrorResult;
    
    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;

    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
    
    
    /**
     * 繳款人明細查詢結果
     */
    private PaginatedList<PayerTemp> queryPayerTempResult;
    
    /**
     * 收款類別選單
     */
    private List<LabelValue> formatDefinitionoOptions;
    
    @SpringBean("uploadFileService")
    private UploadFileService uploadFileService;

    @SpringBean("paymentService")
    private PaymentService paymentService;
    
    @SpringBean("groupService")
    private GroupService groupService;

    @SpringBean("formatDefinitionService")
    private FormatDefinitionService formatDefinitionService;

    @SpringBean("columnValidateErrorService")
    private ColumnValidateErrorService columnValidateErrorService;
    
    @SpringBean("payerTempService")
    private PayerTempService payerTempService;

  
    
    private List<UploadFile> checkUploadFile;


    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        try {
            Calendar cal = Calendar.getInstance();
            qryUploadTo = cal.getTime();
            cal.add(Calendar.MONTH, -1);
            qryUploadFrom = cal.getTime();
        }
        catch (Exception e) {
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 查詢
     * @return
     */
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryUploadFile)
                qryUploadFile = new UploadFile();

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                qryUploadFile.setGroup(group);
            }

            //呼叫服務查詢
            queryResult = uploadFileService.queryByUploadFile(qryUploadFile, qryUploadFrom, qryUploadTo, queryResult);

        }
        catch (Exception e) {
            logger.error("帳單上傳記錄查詢錯誤(Soez9004ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_JSP);
    }

    
    /**
     * 查詢轉入的繳費資料
     * @return
     */
    public Resolution doAjaxQueryFilePayments()
    {
        logger.debug("Enter doAjaxQueryFilePayments mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                qryUploadFile.setGroup(group);
            }

            // 設定查詢條件
            Payment payment = new Payment();
            payment.setGroup(qryUploadFile.getGroup());
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUploadFilePk(qryUploadFile.getUploadFilePk());
            payment.setUploadFile(uploadFile);
            //呼叫服務查詢
            queryPaymentResult = paymentService.queryByPayment(payment, null, null, queryPaymentResult);

        }
        catch (Exception e) {
            logger.error("帳單上傳記錄查詢-帳單內容查詢錯誤(Soez9004ActionBean.doAjaxQueryFilePayments):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_PAYMENT_JSP);
    }
    
    /**
     * 查詢轉入錯誤原因資料
     * @return
     */
    public Resolution doAjaxQueryFileErrorReasons()
    {
        logger.debug("Enter doAjaxQueryFileErrorReasons mehtod.");
        try {
            
            // 設定查詢條件
            ColumnValidateError columnValidateError = new ColumnValidateError();
            columnValidateError.setUploadFile(qryUploadFile);

            //呼叫服務查詢            
            this.queryColumnValidateErrorResult = 
                columnValidateErrorService.queryByColumnValidateError(
                                columnValidateError, queryColumnValidateErrorResult);

        }
        catch (Exception e) {
            logger.error("帳單上傳記錄查詢-查詢轉入錯誤原因(Soez9004ActionBean.doAjaxQueryFileErrorReasons):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_COLUMN_ERROR_JSP);
    }
    
    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception("No Authority");
            }
            

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("帳單上傳記錄查詢-帳單業者查詢錯誤(Soez9004ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }
    
    
    
    
    
    /**
     * 查詢轉入的繳款人資料
     * @return
     */
    public Resolution doAjaxQueryFilePayers()
    {
        logger.debug("Enter doAjaxQueryFilePayers mehtod.");
        try {

            // 設定查詢條件
            PayerTemp qryPayerTemp = new PayerTemp();
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                qryPayerTemp.setGroup(group);
            }
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUploadFilePk(qryUploadFile.getUploadFilePk());
            qryPayerTemp.setUploadFile(uploadFile);
            //呼叫服務查詢
            queryPayerTempResult = payerTempService.queryByPayerTemp(qryPayerTemp, queryPayerTempResult);

        }
        catch (Exception e) {
            logger.error("繳款人內容查詢錯誤(Soez9004ActionBean.doAjaxQueryFilePayers):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_PAYER_JSP);
    }

    
    
       
    

    public Resolution doAjaxGroupNoChange()
    {
        logger.debug("Enter doAjaxGroupNoChange mehtod.");
        return new ForwardResolution(AJAX_FORMT_DEF_OPTIONS_JSP);
    }
    
    /**
     * @return the qryUploadFile
     */
    public UploadFile getQryUploadFile() {
        return qryUploadFile;
    }


    /**
     * @param qryUploadFile the qryUploadFile to set
     */
    public void setQryUploadFile(UploadFile qryUploadFile) {
        this.qryUploadFile = qryUploadFile;
    }


    /**
     * @return the qryUploadFrom
     */
    public Date getQryUploadFrom() {
        return qryUploadFrom;
    }


    /**
     * @param qryUploadFrom the qryUploadFrom to set
     */
    public void setQryUploadFrom(Date qryUploadFrom) {
        this.qryUploadFrom = qryUploadFrom;
    }


    /**
     * @return the qryUploadTo
     */
    public Date getQryUploadTo() {
        return qryUploadTo;
    }


    /**
     * @param qryUploadTo the qryUploadTo to set
     */
    public void setQryUploadTo(Date qryUploadTo) {
        this.qryUploadTo = qryUploadTo;
    }


    /**
     * @return the queryResult
     */
    public PaginatedList<UploadFile> getQueryResult() {
        return queryResult;
    }


    /**
     * @param queryResult the queryResult to set
     */
    public void setQueryResult(PaginatedList<UploadFile> queryResult) {
        this.queryResult = queryResult;
    }

    
    /**
     * @return the queryPaymentResult
     */
    public PaginatedList<Payment> getQueryPaymentResult() {
        return queryPaymentResult;
    }

    
    /**
     * @param queryPaymentResult the queryPaymentResult to set
     */
    public void setQueryPaymentResult(PaginatedList<Payment> queryPaymentResult) {
        this.queryPaymentResult = queryPaymentResult;
    }

    
    /**
     * @return the qryGroup
     */
    public Group getQryGroup() {
        return qryGroup;
    }

    
    /**
     * @param qryGroup the qryGroup to set
     */
    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }

    
    /**
     * @return the queryGroupResult
     */
    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }

    
    /**
     * @param queryGroupResult the queryGroupResult to set
     */
    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }

    
    
    /**
     * @return the queryColumnValidateErrorResult
     */
    public PaginatedList<ColumnValidateError> getQueryColumnValidateErrorResult() {
        return queryColumnValidateErrorResult;
    }

    
    /**
     * @param queryColumnValidateErrorResult the queryColumnValidateErrorResult to set
     */
    public void setQueryColumnValidateErrorResult(PaginatedList<ColumnValidateError> queryColumnValidateErrorResult) {
        this.queryColumnValidateErrorResult = queryColumnValidateErrorResult;
    }

    /**
     * @return the formatDefinitionoOptions
     */
    public List<LabelValue> getFormatDefinitionoOptions() {
        if (null == this.formatDefinitionoOptions)
        {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                // 查詢條件
                FormatDefinition formatDefinition = new FormatDefinition();
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                formatDefinition.setGroup(group);
                if (null == this.qryUploadFile || null == this.qryUploadFile.getFormatDefinition() || null == this.qryUploadFile.getFormatDefinition().getFormatType())
                    formatDefinition.setFormatType(new Integer(1));
                else
                    formatDefinition.setFormatType(this.qryUploadFile.getFormatDefinition().getFormatType());
                formatDefinition.setDeleted(Boolean.FALSE);
                formatDefinitionoOptions = formatDefinitionService.findLabelValueByFormatDefinition(formatDefinition,true);
            }
            else
            {
                // 銀行端，看是否有群組代碼，若沒有則回傳空陣列
                if (null != this.getQryUploadFile() && null != this.getQryUploadFile().getGroup())
                {
                    // 查詢條件
                    FormatDefinition formatDefinition = new FormatDefinition();
                    formatDefinition.setGroup(this.getQryUploadFile().getGroup());
                    if (null == this.qryUploadFile || null == this.qryUploadFile.getFormatDefinition() || null == this.qryUploadFile.getFormatDefinition().getFormatType())
                        formatDefinition.setFormatType(new Integer(1));
                    else
                        formatDefinition.setFormatType(this.qryUploadFile.getFormatDefinition().getFormatType());
                    formatDefinition.setDeleted(Boolean.FALSE);
                    formatDefinitionoOptions = formatDefinitionService.findLabelValueByFormatDefinition(formatDefinition, true);
                }
                else
                {
                    this.formatDefinitionoOptions = new ArrayList<LabelValue>();                    
                }

            }
            
        }
        return formatDefinitionoOptions;
    }

    
    /**
     * @param formatDefinitionoOptions the formatDefinitionoOptions to set
     */
    public void setFormatDefinitionoOptions(List<LabelValue> formatDefinitionoOptions) {
        this.formatDefinitionoOptions = formatDefinitionoOptions;
    }

    /**
     * @param checkUploadFile the checkUploadFile to set
     */
    public void setCheckUploadFile(List<UploadFile> checkUploadFile) {
        this.checkUploadFile = checkUploadFile;
    }

    /**
     * @return the checkUploadFile
     */
    public List<UploadFile> getCheckUploadFile() {
        return checkUploadFile;
    }
    

    
    /**
     * @return the queryPayerTempResult
     */
    public PaginatedList<PayerTemp> getQueryPayerTempResult() {
        return queryPayerTempResult;
    }

    
    /**
     * @param queryPayerTempResult the queryPayerTempResult to set
     */
    public void setQueryPayerTempResult(PaginatedList<PayerTemp> queryPayerTempResult) {
        this.queryPayerTempResult = queryPayerTempResult;
    }

    
    
    
    
    
    
    
    
}
